from django.conf import settings
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.skus_images_serializers import ImageSeriazlier, SkuSeriazlier
from apps.meiduo_admin.utils.pagenum import PageNum
from fdfs_client.client import Fdfs_client

class SkusImagesView(ModelViewSet):
    queryset = SKUImage.objects.all().order_by("-id")
    serializer_class = ImageSeriazlier
    # 分页
    pagination_class = PageNum
    def create(self,request,*args,**kwargs):
        # 接受数据
        sku = request.data.get("sku")
        image = request.data.get("image")
        # 验证数据
        if not all([sku,image]):
            return Response({"detial":"数据不完整"},status=400)
        # 处理
        image_client = Fdfs_client(settings.FASTDFS_PATH)
        # 上传图片   文件不在本地时用upload_by_buffer
        data = image_client.upload_by_buffer(image.read())
        image_name = data.get("Remote file_id")
        # 创建模型类对象
        instance = SKUImage.objects.create(sku_id=sku,image=image_name)
        seriazlier = self.get_serializer(instance)
        return Response(seriazlier.data,status=201)
    def update(self, request, *args, **kwargs):
        # 获取当前修改的图片对象
        instance = self.get_object()
        # 接受
        sku_id = request.data.get("sku")
        image = request.data.get("image")
        # 验证
        if not all([sku_id]):
            return Response({"detial":"数据不完整"},status=400)
        # 处理
        # 将新图片保存到fdfs  删除就图片  上传新图片
        if image:
            image_client = Fdfs_client(settings.FASTDFS_PATH)
            # 上传图片  先删除就文件
            # instance.image.name获取图片名称字符串
            image_client.delete_file(instance.image.name)
            print("------------------------")
            a = instance.image
            b = instance.image.name
            print(a,type(a))
            print(b,type(b))
            data = image_client.upload_by_buffer(image.read())
            instance.image = data.get("Remote file_id")
        # 修改对象
        instance.sku_id = sku_id
        instance.save()
        seriazlier = self.get_serializer(instance)
        # 响应
        return Response(seriazlier.data,status=201)
    # 图片的删除
    def destroy(self, request, *args, **kwargs):
        # 查询当前对象
        instance = self.get_object()
        # 删除图片
        image_client = Fdfs_client(settings.FASTDFS_PATH)
        image_client.delete_file(instance.image.name)
        # 删除数据
        instance.delete()
        return Response(status=204)


# 获取所有的sku
class SkuSimpleView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SkuSeriazlier
